package movee.os;

import movee.config.AppProperties;
import movee.utils.FileUtils;
import movee.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.time.LocalDateTime;
import java.util.Locale;

/**
 * 处理文件系统相关的任务
 *
 * @author movee
 */
@Service
@Slf4j
public class FileSystemService {

    private final AppProperties appProperties;

    public FileSystemService(AppProperties appProperties) {
        this.appProperties = appProperties;
    }

    /**
     * 创建目录
     * @param dateTime datetime
     * @param idc idc
     * @return true or false
     */
    public boolean createDirectoryIfNeeded(LocalDateTime dateTime, String idc) {

        if (dateTime != null && !StringUtils.isEmpty(idc)) {
            String currDate = TimeUtils.getStringDateFromDateTime(dateTime);

            String dir = appProperties.getLatestCfgDir() + File.separator + currDate
                    + File.separator + idc.toLowerCase(Locale.ROOT);
            try {
                FileUtils.createDirecotryIfNotExist(dir);
            } catch (Throwable t) {
                log.error("createDirectoryIfNeeded failed. dir: {}, stack: {}", dir, ExceptionUtils.getStackTrace(t));
            }
        }

        return false;
    }

    /**
     * 获取输入流，直到输入结束
     * @param inputStream inputStream
     * @return echo result
     */
    public String readInputStream(InputStream inputStream) {
        StringBuilder sb = new StringBuilder();
        try {
            InputStreamReader reader = new InputStreamReader(inputStream);
            BufferedReader buffer = new BufferedReader(reader);
            String line = buffer.readLine();
            while (line != null) {
                sb.append(line).append("\n");
                line = buffer.readLine();
            }
        } catch (Throwable t) {
            log.warn("readInputStream failed. except stack: {}", ExceptionUtils.getStackTrace(t));
        }

        return sb.toString();
    }

}
